﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pigmalion.BusinessEntities;
using Pigmalion.BusinessLogic;
using System.ComponentModel;
using System.Diagnostics;

namespace Pigmalion.Presenter.ProductoPresenter
{
    public partial class ProductoPresenter
    {
        private readonly IProductoView _view;
        private ProductoBL factory;
        private BackgroundWorker bw;
        private Stopwatch stw;

        public ProductoPresenter(IProductoView view)
        {
            _view = view;

            stw = new Stopwatch();
            
            factory = new ProductoBL();
            bw = new BackgroundWorker();
           

            bw.WorkerReportsProgress = true;

            bw.RunWorkerCompleted += (sender, e) => 
            { 
            _view.GetAllFromProductos = e.Result as List<Producto>;
            };

            bw.ProgressChanged += (sender, e) => { _view.ProgressPercentage = e.ProgressPercentage; };
        }

        public void CargarProducto()
        {
            bw.DoWork += (sender, e) => 
            {
                
                bw.ReportProgress(20);
                stw.Start();
                //System.Threading.Thread.Sleep(500);
                e.Result = factory.GetAllFromProduto();
                stw.Stop();
                bw.ReportProgress(100);

                TimeSpan ts = stw.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                    ts.Hours, ts.Minutes, ts.Seconds,
                                                    ts.Milliseconds / 10);
                _view.Time = elapsedTime;
            };

            if (!bw.IsBusy)
            {
                bw.RunWorkerAsync("Ejecutando Consulta");
            }            
        }

        public void BuscarProductoByCriterio(string criterio)
        {
            

            bw.DoWork += (sender, e) =>
            {
                          
                bw.ReportProgress(20);
                //System.Threading.Thread.Sleep(500);
                stw.Restart();
                e.Result = factory.GetFromProdutoByDescripcion(criterio);
                stw.Stop();
                bw.ReportProgress(100);

                TimeSpan ts = stw.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                    ts.Hours, ts.Minutes, ts.Seconds,
                                                    ts.Milliseconds / 10);
                _view.Time = elapsedTime;
            };

            if (!bw.IsBusy)
            {
                bw.RunWorkerAsync("Ejecutando Consulta");
            }            
        }

    }
}
